package com.yzpc.service.Impl;

import com.yzpc.entity.MouseClick;
import com.yzpc.entity.Script;
import com.yzpc.mapper.MouseClickMapper;
import com.yzpc.mapper.ScriptMapper;
import com.yzpc.service.IScriptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class IScriptServiceImpl implements IScriptService {

    @Autowired
    private ScriptMapper scriptMapper;

    @Autowired
    private MouseClickMapper mouseClickMapper;

    @Override
    public int insertScript(Script script) {
        return scriptMapper.insertScript(script);
    }

    @Override
    public int updateScript(Script script) {
        return scriptMapper.updateScript(script);
    }

    @Override
    public void deleteScriptById(Integer scriptId) {
        scriptMapper.deleteScriptById(scriptId);
    }

    @Override
    public void deleteScriptByName(String  userName) {
        scriptMapper.deleteScriptByName(userName);
    }

    @Override
    public List<Script> findScriptList(Script script) {
        return scriptMapper.findScriptList(script);
    }

    @Override
    public Script findScriptById(Integer scriptId) {
        return scriptMapper.findScriptById(scriptId);
    }

    @Override
    public List<Script> findScriptByName(String userName) {
        return scriptMapper.findScriptByName(userName);
    }

    @Override
    public List<MouseClick> getMouseClicks() {
        return mouseClickMapper.getMouseClicksWithoutScriptId();
    }

    @Override
    public void saveScript(String scriptName, List<MouseClick> actions, String userName) {
        StringBuilder scriptContentBuilder = new StringBuilder();
        for (MouseClick action : actions) {
            scriptContentBuilder.append("(").append(action.getX()).append(", ").append(action.getY()).append("),");
        }

        String scriptContent = scriptContentBuilder.toString();
        // 去掉最后的逗号
        if (!scriptContent.isEmpty()) {
            scriptContent = scriptContent.substring(0, scriptContent.length() - 1);
        }

        Script script = new Script();
        script.setScriptName(scriptName);
        script.setScriptContent(scriptContent);
        script.setUserName(userName); // 设置用户名
        scriptMapper.insertNewScript(script);

        // 获取刚插入的 script_id
        Integer generatedScriptId = script.getScriptId();

        // 更新 mouse_clicks 表中的 script_id
        mouseClickMapper.updateMouseClickScriptId(generatedScriptId);
    }
//    启动
@Override
    public int updateScriptUsed(Integer scriptId, int used) {
        return scriptMapper.updateScriptUsed(scriptId, used);
    }
}